package com.lb.api;

import lombok.Data;
import org.slf4j.MDC;

import static com.lb.api.ApiResultCodeEnum.SUCCESS;
import static com.lb.base.constants.BaseConstants.MDC_KEY_TRACE_ID;


/**
 * 请求结果
 *
 * @author xiemingzhi
 * @since 1.0
 */
@Data
public class ApiResult<T> {
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 数据
     */
    private T data;
    /**
     * 前端显示文案
     */
    private String message;
    /**
     * 链路编号
     */
    private String traceId;

    public static <T> ApiResult<T> success() {
        return build(SUCCESS.getCode(), SUCCESS.getReason(), null);
    }

    public static <T> ApiResult<T> success(T data) {
        return build(SUCCESS, data);
    }

    public static <T> ApiResult<T> build(ApiResultCode apiResultCode) {
        return build(apiResultCode.getCode(), apiResultCode.getReason(), null);
    }

    public static <T> ApiResult<T> build(ApiResultCode resultCode, T data) {
        return build(resultCode.getCode(), resultCode.getReason(), data);
    }

    public static <T> ApiResult<T> build(ApiResultCode apiResultCode, String message, T data) {
        return build(apiResultCode.getCode(), message, data);
    }

    public static <T> ApiResult<T> build(Integer code, String message, T data) {
        ApiResult<T> apiResult = new ApiResult<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(message);
        apiResult.setTraceId(MDC.get(MDC_KEY_TRACE_ID));
        return apiResult;
    }
}
